import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '../store';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';
import defaultRouters from './defaultRouters';

NProgress.configure({ showSpinner: false });

// 消除重复进入相同路由的警报
// push方式
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err);
};

// replace方式
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err);
};

Vue.use(VueRouter);

const router = new VueRouter({
    base: process.env.BASE_URL,
    routes: defaultRouters
});

// 路由拦截
router.beforeEach(async(to, from, next) => {
    NProgress.start();
    // 注意：如果想不通过Nginx的方式访问项目，则在此固定写入token值，token值可通过登录线上地址获取，在联调接口阶段再还原注释
    // let tokenValue =
    //   'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxNCwibmFtZSI6Iuefs-ahguWchiIsImF2YXRhciI6IiIsImV4cCI6MTYyNTYyMzM0NywiaXNzIjoiaGlnbnRvbiIsIm5iZiI6MTYyNTUzNjk0N30.OKk4GnKWhULbYm5OXGWcO7yVzFrLo5qnBBt1zRfcaQ4';
    // localStorage.setItem('token', tokenValue);
    let token = localStorage.getItem('token');
    if (token) {
        if (store.getters.routes.length) {
            next();
        } else {
            await store.dispatch('permission/generateRoutes');
            next({
                path: to.path,
                query: to.query,
                replace: true
            });
        }
    } else {
        store.commit('user/signOut', to.path);
    }
});

router.afterEach((to, from, next) => {
    NProgress.done();
    document.title = to.meta.title || '长泰智能装备云平台';
});

export default router;
